﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Globalization;

namespace Chip8
{
    public partial class frmBreakpoint : Form
    {
        public frmEmu Mainform;
        public bool Addnew = false;
        public int SelectedIndex;
        string Flags = "";
        public frmDebugger DB;
        public frmBreakpoint()
        {
            InitializeComponent();
        }

        public string BreapPointText
        {
            get { return Flags; }
         }

        private void cmdok_Click(object sender, EventArgs e)
        {
            if (txtaddress.Text != "" && OnlyHexInString(txtaddress.Text))
            {
                if (ushort.Parse(txtaddress.Text, NumberStyles.HexNumber) > Mainform.MainSystem.Memory.Length - 1)
                {
                    MessageBox.Show("Please enter a valid 4 digit address within the bounds of memory.", "Invalid Address", MessageBoxButtons.OK);
                    txtaddress.Focus();
                    return;
                }

                if (Addnew)
                    DB.Breakpoints.Add(new frmDebugger.Breakpoint(txtaddress.Text.PadLeft(4, '0'), chkread.Checked, chkwrite.Checked, chkexecute.Checked));
                else
                {
                    DB.Breakpoints[SelectedIndex].Address = txtaddress.Text.PadLeft(4,'0');
                    DB.Breakpoints[SelectedIndex].Read = chkread.Checked;
                    DB.Breakpoints[SelectedIndex].Write = chkwrite.Checked;
                    DB.Breakpoints[SelectedIndex].Execute = chkexecute.Checked;
                }

                Flags = txtaddress.Text.PadLeft(4, '0');

                if (chkread.Checked)
                    Flags += " -R";
                if (chkwrite.Checked)
                    Flags += " -W";
                if (chkexecute.Checked)
                    Flags += " -E";

            }
            else { this.DialogResult = DialogResult.None;  MessageBox.Show("Invalid entry for 'Address'. Please try again.", "Invalid Address", MessageBoxButtons.OK); txtaddress.Focus(); }
        }

        public bool IsHex(string C)
        {
            Match m = Regex.Match(C, "[A-F0-9]");
            if (m.Success)
                return false;

            return true;
        }

        public bool OnlyHexInString(string test)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
        }

        private void txtaddress_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar != Keys.Back && ModifierKeys != Keys.Control)
            e.Handled = IsHex(e.KeyChar.ToString().ToUpper());
        }

    }
}
